// pages/tousu/tousu.js
const app = getApp();
const url = app.globalData.url;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    value:'',
    imgList:[],
    fbs:false,
    loding:true,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (o) {
    console.log(o)
    if(o.id){
      this.setData({id:o.id,tt:o.tt});
      this.peizi();
    }else{
      wx.showModal({
        title: '提示',
        content: '系统错误',
        success(res){
          if (res.cancel) {
            //点击取消,默认隐藏弹框
            // if (options.finish) {
              wx.navigateBack({ delta: 1 })
            // }
          } else {
              wx.navigateBack({ delta: 1 })
          }
        }
      })
    }
  },
  addfbts(){
    let that=this;
    let imgs=that.data.imgList,user=that.data.user,val=that.data.value;
    var img="";
    for(var p of imgs){
      img+=p.substring(p.indexOf('img'))+',';
    }
    img = img.substring(0,img.length-1);
    let sj={
      did:that.data.id,
      tt:that.data.tt,
      uname:user.uname?user.uname:user.nickName,
      uid:user.uid,
      tslx:'fbxx',
      img: img,
      datalr:that.data.value
    };
    app.fetch('api/wx/addts', sj, "GET", (err, data) => {
      console.log(data)
      if (data.code == 200) {
        this.setData({fbs:true})
        wx.showToast({
          title: "投诉成功",
          icon: 'success',
          duration: 1000
        });
        setTimeout(function () {
          wx.navigateBack({
            data: 1
          })
        }, 1000)
      }
    })
  },
  //放大图片
  previewImage: function (e) {
    var src = e.currentTarget.dataset.src ; //获取data-src
    var imgList = this.data.imgList; //获取data-list
    //要把对象中需要的键值对拿出来，放进一个数组，Object.keys是为了取到对象的长度进行遍历
    var imgArr = [];
    var objkeys = Object.keys(imgList);
    for (var i = 0; i < objkeys.length; i++) {
      imgArr.push(imgList[i] );
    }
    //图片预览
    wx.previewImage({
      current: src, // 当前显示图片的http链接
      urls: imgArr // 需要预览的图片http链接列表
    })
  },
  // 上传logo图片
  addimglogo(){
    let that=this;
    let num =5-that.data.imgList.length;
    if(num>0){
      wx.chooseImage({
        count:num,
        sizeType: ['original', 'compressed'],
        sourceType: ['album', 'camera'],
        success: function(res) {
          var img = res.tempFilePaths;
          for (let p of img) {
            that.upload(p,'tstp');
            console.log(p)
          }
        },
        fail: function(res) {},
        complete: function(res) {},
      })
    }else{
      wx.showToast({
        title: '一次最多'+that.data.peizi.xcxadd.logos.txt+'张图片',//提示文字
        duration: 1000,//显示时长
        mask: false,//是否显示透明蒙层，防止触摸穿透，默认：false  
        image: '../../img/ico/clear.png', //图标，支持"success"、"loading"  
      })
    }
  },
  // 上传图片
  upload:function (img,lx) {
    wx.showToast({
      icon: "loading",
      title: "上传图片中..."
    });
    let that=this;
    wx.uploadFile({
      url: url + 'img/sctp.php', //接口
      filePath: img,
      name: 'file',
      formData: {
        'user': that.data.user.uid,
        lx:lx
      },
      success: function (res) {
        var data = res.data;
        if(!data.code){
          data = JSON.parse(data);
        }
        console.log(res)
        if (data.code == 200) {
            let imgList = that.data.imgList;
            let img1 = url +  data.uptp;
            imgList.push(img1);
            that.setData({  imgList: imgList });
          }
        //do something
      },
      fail: function (error) {
        console.log(error);
      }
    })
  },
  //删除图片
  clearimg: function (e) {
    wx.showLoading({
      title: '删除中...',
    })
    let that = this;
    let i = e.currentTarget.dataset.index;
    let imgList = this.data.imgList;
    let tp = [];
    let delimg = imgList[i].substring(imgList[i].indexOf('img')+4);
    wx.request({
      url: url + 'img/deltp.php', //接口地址
      data: {
        img: delimg
      },
      method: "POST",
      header: {
        "Content-Type": "application/x-www-form-urlencoded" // 默认值
      },
      success(res) {
        console.log(res)
        if (res.data.code == 200) {
          for (let p of imgList) {
            console.log(p)
            if (p != imgList[i]) {
              console.log(p)
              tp.push(p);
            }
            that.setData({ imgList: tp })
          }
        } else {
          wx.showModal({
            title: '失败',
            content: res.data,
            showCancel: false,//是否显示取消按钮
            cancelText: "否",//默认是“取消”
            cancelColor: 'skyblue',//取消文字的颜色
            confirmText: "是",//默认是“确定”
            confirmColor: 'skyblue',//确定文字的颜色
            success: function (res) {
            },
            fail: function (res) { },//接口调用失败的回调函数
            complete: function (res) { },//接口调用结束的回调函数（调用成功、失败都会执行）
          })
        }
        wx.hideLoading()
      }
    })
  },
   // 执行删除
   delsc: function (img) {
    let that = this;
    wx.request({
      url: url + 'img/deltp.php', //接口地址
      data: {
        img: img
      },
      method: "POST",
      header: {
        "Content-Type": "application/x-www-form-urlencoded" // 默认值
      },
      success(res) {
        console.log(res)
      }
    })
  },
   //失去焦点时
  bindblur: function (e) {
    this.setData({ value: this.trim(e.detail.value) })
  },
  subtn(e){
    this.setData({ value:e.detail.value})
    console.log(e)
  },
  trim: function (s) {
    return s.replace(/(^\s*)|(\s*$)/g, "");
  },
  // 配置文件
  peizi: function () {
    let that = this;
    app.fetch('api/wx/getpeizi', { dlx: 'xcxadd' }, "GET", (err, data) => {
      console.log(data)
      if (data.code == 200) {
        wx.setNavigationBarTitle({
          title: "投诉-"+that.data.tt
        });
        that.setData({
          peizi: data.data,
        });
        that.hquser();
      } else {
        wx.showModal({
          title: '接口数据错误',
          content: '接口:"' + url + 'api/wx/getpeizi.php' + '",msg:' + data.msg,
          showCancel: false,//是否显示取消按钮
          confirmText: "好的",//默认是“确定”
          confirmColor: 'skyblue',//确定文字的颜色
          success: function (res) {

          },
          fail: function (res) { },//接口调用失败的回调函数
          complete: function (res) { },//接口调用结束的回调函数（调用成功、失败都会执行）
        })
      }
    })
  },
  // 获取user信息;
  hquser() {
    let that = this;
    wx.getStorage({
      key: 'openid',
      success(res) {
        app.fetch('api/wx/user', { openid: res.data }, "POST", (err, data) => {
          if (data.code == 200) {
            that.setData({ user: data.data[0],loding:false})
            // that.getcsData();
          }
        })
      },
      fail(){
        wx.showModal({
          title: '提示',
          content: '请先登录',
          success(res){
            if (res.cancel) {
              //点击取消,默认隐藏弹框
              // if (options.finish) {
                wx.navigateBack({ delta: 1 })
              // }
            } else {
                wx.redirectTo({
                  url: "/pages/my/my"
                })
            }
          }
        })
      }
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    let that = this;
    let tp = that.data.imgList;
    if (!this.data.fbs) {
      console.log("执行删除");
      if (tp.length > 0) {
        for (let p of tp) {
          let img = p.substring(p.indexOf('img') + 4);
          that.delsc(img);
        }
      }
    }
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  // onShareAppMessage: function () {

  // }
})